/**
 * Copyright 2009-2010 - YangJiandong(chunquedong)
 * 
 * This file is part of ChunMap project
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE(Version >=3)
 * 你可以自由复制、传播本项目的下载包文件，但必须保持其完整性。
 * 我们不用对使用中的风险及由此造成的损失承担任何责任。
 * 详细情况请见《ChunMap许可协议》。

 * 想了解更多有关ChunMap的信息，请访问http://code.google.com/p/chunmap/
 */
package chunmap.app.tools;

import java.awt.AWTEvent;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.event.MouseEvent;
import java.util.List;

import chunmap.app.bench.AbstractTool;
import chunmap.app.bench.EventType;
import chunmap.data.feature.Feature;
import chunmap.data.provider.LayerFactory;
import chunmap.model.coord.Transform;
import chunmap.model.elem.Envelope;
import chunmap.util.CMEventListenerList;
import chunmap.view.layer.Layer;
import chunmap.view.layer.VectorLayer;
import chunmap.view.render.ArrowSymbol;
import chunmap.view.render.GeneralSymbol;
import chunmap.view.render.Style2D;
import chunmap.view.render.Symbol;

/**
 * @author chunquedong
 * 
 */
public class SelectTool extends AbstractTool {

	private void mouseClicked(MouseEvent e) {
		double x = e.getX();
		double y = e.getY();
		double d = 5d;
		double minx = x - d;
		double miny = y - d;
		double maxx = x + d;
		double maxy = y + d;
		Envelope env = new Envelope(minx, miny, maxx, maxy);
		Transform trans = map.getView().screen2World();
		Envelope env2 = env.transform(trans);
		select(env2);
	}
	
	public CMEventListenerList onSelectChange=new CMEventListenerList();

	private void select(Envelope env) {

		SelectIterator it = new SelectIterator(env);
		List<Layer> layers = map.getLayerCollection().getLayers();
		for (Layer layer : layers) {
			if (layer instanceof VectorLayer) {
				VectorLayer vl = (VectorLayer) layer;
				if (vl.isSelectabel()){
					vl.getFeatures().select(map.getView().getBufferEnvelop(), it);
				}
			}
		}
		finish(it.features);
		onSelectChange.fire(it.features);
		map.refreshMap();
	}
	
	public void finish(List<Feature> features) {
		if (features.size() == 0)
        {
            map.getLayerCollection().setSelectedLayer(null);
            return;
        }
		
		VectorLayer layer = (VectorLayer) LayerFactory.createFeatureLayer(features);
		Style2D style = new Style2D();
		style.setNeedArea(false);

		final ArrowSymbol symbol = new ArrowSymbol();
		
		style.setPointSize(15);
		style.setLineColor(Color.magenta);
		style.setStroke(new BasicStroke(3));
		style.setPointColor(Color.magenta);

		layer.setDefaultStyle(new Symbol[]{new GeneralSymbol(style),symbol});
		map.getLayerCollection().setSelectedLayer(
				layer);
	}

	@Override
	public boolean actionEvent(AWTEvent event, EventType type) {
		if (MouseEvent.MOUSE_CLICKED != event.getID()) return true;
		
		MouseEvent e = (MouseEvent) event;
		mouseClicked(e);
		
		return true;
	}
}
